<template>
  <view class="min-h-screen bg-gray-100">
    <!-- 顶部背景区域 -->
    <view class="relative">
      <view
        class="h-60 w-full bg-cover bg-center"
        style="background-image: url('https://ceshiweb.picaime.com/static/images/user/top-background.png');"
      />

      <!-- 用户信息区域 -->
      <view class="absolute left-4 right-4 top-14 flex items-center">
        <view class="avatar-container">
          <up-icon name="account-fill" size="40" color="#fff"/>
        </view>
        <view class="ml-3 flex-1">
          <text class="text-lg text-[#333] font-bold">
            {{ cashierUserInfo?.admin?.real_name }}
          </text>
          <view class="mt-1 flex items-center">
            <text class="text-sm text-[#666]">
              {{ cashierUserInfo?.name }}
            </text>
            <text class="ml-2 text-sm text-[#666]">
              {{ cashierUserInfo?.mobile }}
            </text>
          </view>
          <view v-if="cashierUserInfo?.admin?.username" class="mt-1">
            <text class="text-sm text-[#666]">
              档口负责人：{{ cashierUserInfo?.admin?.username }}
            </text>
          </view>
        </view>
        <image
          class="h-6 w-6"
          src="https://ceshiweb.picaime.com/static/images/user/right.png"
          mode="aspectFit"
        />
      </view>

      <!-- 会员信息卡片 -->
      <view v-if="userInfo.outtime" class="absolute bottom-1 left-0 right-0 px-4">
        <view
          class="h-24 w-full overflow-hidden rounded-lg bg-cover bg-center"
          style="background-image: url('https://ceshiweb.picaime.com/static/images/user/info.png');"
        />
        <view class="absolute bottom-0 left-0 right-0 top-0 flex">
          <view class="item-center ml-[45rpx] mt-2 flex flex-1 flex-col">
            <view class="mb-1 flex">
              <image
                class="mr-1 h-5 w-5"
                src="https://ceshiweb.picaime.com/static/images/user/diamond.png"
                mode="aspectFit"
              />
              <view
                class="h-[44rpx] w-[190rpx] flex items-center justify-center rounded-[46rpx] bg-[rgba(56,56,56,0.61)]"
              >
                <text class="text-sm text-yellow-400 font-medium">
                  专业档口版
                </text>
              </view>
            </view>
            <text
              class="mt-2 text-[30rpx] font-normal leading-[41rpx]"
              style="color: rgb(255 235 214 / 34%); letter-spacing: 0;"
            >
              到期时间：{{ formatExpireTime(userInfo.outtime) }}
            </text>
          </view>
          <button
            class="mr-[45rpx] mt-4 h-[72rpx] w-[202rpx] flex items-center justify-center rounded-[46rpx] text-sm text-[#705336]"
            style="background: linear-gradient(160.91deg, rgb(239 204 152 / 100%) 0%, rgb(222 174 104 / 100%) 100%); box-shadow: inset -2px -2px 2px rgb(82 54 20 / 25%), inset 2px 2px 4px rgb(255 244 191 / 61%);"
            @click="renew"
          >
            立即续费
          </button>
        </view>
      </view>

      <!-- 功能菜单区域 -->
      <view class="absolute left-0 right-0 flex justify-center -bottom-23">
        <view
          class="mx-auto w-[800rpx] overflow-hidden bg-center bg-no-repeat"
          style=" height: 270rpx;background-image: url('https://ceshiweb.picaime.com/static/images/user/menu-background.png'); background-size: 108% 100%;"
        />
        <view class="absolute inset-0 flex items-center justify-center">
          <view class="w-[95%] flex justify-evenly">
            <view
              v-for="menu in menus"
              :key="menu.id"
              class="flex flex-col items-center"
              @click="navigate(menu)"
            >
              <image class="h-[50rpx] w-[50rpx]" :src="menu.icon" mode="aspectFit"/>
              <text class="mt-2 text-xs text-gray-500">
                {{ menu.name }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 设置列表 -->
    <view class="mx-4 mt-24 overflow-hidden rounded bg-white">
      <view
        v-for="item in settingsList"
        :key="item.id"
        class="h-[100rpx] flex items-center justify-between border-b border-gray-100/30"
        @click="navigate(item)"
      >
        <text class="ml-5 text-[30rpx] text-gray-800">
          {{ item.name }}
        </text>
        <view class="mr-5 flex items-center">
          <text v-if="item.description" class="mr-3 text-[26rpx] text-gray-400">
            {{
              item.description
            }}
          </text>
          <image
            class="h-[28rpx] w-[16rpx]"
            src="https://ceshiweb.picaime.com/static/images/user/right.png"
            mode="aspectFit"
          />
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="mx-4 mb-6 mt-4">
      <button
        class="h-[100rpx] w-full flex items-center justify-center border-0 rounded bg-white"
        @click="handleLogout"
      >
        <text class="text-[30rpx] text-red-500">
          退出登录
        </text>
      </button>
    </view>

    <!-- 打印机选择对话框 -->
    <view
      v-if="selectPrinterShow"
      class="printer-modal"
      @click.self="selectPrinterShow = false"
    >
      <view class="printer-modal-content">
        <view class="printer-modal-header">
          <text class="header-title">
            打印机列表
          </text>
          <view class="header-actions">
            <button class="add-feie-btn" size="mini" @click="addFeiyePrinter">
              添加飞蛾打印机
            </button>
            <text class="close-icon" @click="selectPrinterShow = false">
              ✕
            </text>
          </view>
        </view>

        <!-- Loading -->
        <view v-if="searchLoading" class="loading-mask">
          <view class="loading-content">
            <view class="loading-icon"/>
            <text>{{ elementLoadingText }}</text>
          </view>
        </view>

        <scroll-view class="printer-list" scroll-y>
          <!-- 空状态提示 -->
          <view
            v-if="
              usbDevice.length === 0
                && blueDevice.length === 0
                && printerList.length === 0
            "
            class="empty-tip"
          >
            <text>暂无打印机设备</text>
            <text class="sub-tip">
              点击底部“搜索”按钮搜索蓝牙设备
            </text>
          </view>

          <!-- USB 打印机 -->
          <view
            v-for="(item, index) in usbDevice"
            :key="`usb-${index}`"
            class="printer-item"
          >
            <view class="printer-info">
              <view class="info-row">
                <text class="label">
                  打印机名称：
                </text>
                <text class="value">
                  {{ item.deviceName }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  打印机Id：
                </text>
                <text class="value">
                  {{ item.deviceId }}
                </text>
              </view>
              <text class="printer-note">
                备注
                <text class="note-text">
                  这是USB打印机
                </text>
              </text>
            </view>
            <view class="printer-actions">
              <button
                v-if="connectDeviceId === item.id"
                type="warn"
                size="mini"
                @click="disconnectPrint"
              >
                断开连接
              </button>
              <button v-else type="primary" size="mini" @click="selectlyPrint(item, 1)">
                连接
              </button>
            </view>
          </view>

          <!-- 蓝牙打印机 -->
          <view
            v-for="(item, index) in blueDevice"
            :key="`blue-${index}`"
            class="printer-item"
          >
            <view class="printer-info">
              <view class="info-row">
                <text class="label">
                  蓝牙名称：
                </text>
                <text class="value">
                  {{ item.name }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  蓝牙地址：
                </text>
                <text class="value">
                  {{ item.address }}
                </text>
              </view>
              <text class="printer-note">
                备注
                <text class="note-text">
                  这是蓝牙打印机
                </text>
              </text>
            </view>
            <view class="printer-actions">
              <button
                v-if="connectDeviceId === item.address"
                type="warn"
                size="mini"
                @click="disconnectPrint"
              >
                断开连接
              </button>
              <button v-else type="primary" size="mini" @click="selectlyPrint(item, 2)">
                连接
              </button>
            </view>
          </view>

          <!-- 飞蛾打印机 -->
          <view
            v-for="(item, index) in printerList"
            :key="`feie-${index}`"
            class="printer-item feiye-item"
          >
            <view class="printer-info" @click="selectFeiyePrint(item)">
              <view class="info-row">
                <text class="value bold">
                  {{ item.name }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  设备编号：
                </text>
                <text class="value">
                  {{ item.num }}
                </text>
              </view>
              <view class="info-row">
                <text class="label">
                  设备Key：
                </text>
                <text class="value">
                  {{ item.key }}
                </text>
              </view>
              <view v-if="item.note" class="info-row note-row">
                <text class="printer-note">
                  备注
                  <text class="note-text">
                    {{ item.note }}
                  </text>
                </text>
              </view>
            </view>
            <view class="printer-actions">
              <view class="action-btn edit-btn" @click.stop="editFeiyePrinter(item)">
                <up-icon name="edit-pen-fill" size="18" color="#409EFF"/>
              </view>
              <view class="action-btn delete-btn" @click.stop="deleteFeiyePrinter(item.id)">
                <up-icon name="trash-fill" size="18" color="#F56C6C"/>
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 搜索按钮 -->
        <view class="printer-footer">
          <button class="search-btn" @click="searchPrint">
            <text>搜索蓝牙设备</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 添加/编辑飞蛾打印机对话框 -->
    <view v-if="showFeiyeDialog" class="feiye-modal" @click.self="showFeiyeDialog = false">
      <view class="feiye-modal-content" @click.stop>
        <view class="feiye-header">
          <text class="feiye-title">
            {{ feiyeForm.id ? '编辑' : '添加' }}飞蛾打印机
          </text>
          <text class="feiye-close" @click="showFeiyeDialog = false">
            ✕
          </text>
        </view>
        <view class="feiye-body">
          <view class="form-item">
            <view class="label-box">
              <text class="required">
                *
              </text>
              <text class="form-label">
                打印机名称
              </text>
            </view>
            <input
              v-model="feiyeForm.name"
              class="form-input"
              placeholder="请输入打印机名称"
            >
          </view>
          <view class="form-item">
            <view class="label-box">
              <text class="required">
                *
              </text>
              <text class="form-label">
                打印机编号
              </text>
            </view>
            <input
              v-model="feiyeForm.num"
              class="form-input"
              placeholder="请输入打印机编号"
            >
          </view>
          <view class="form-item">
            <view class="label-box">
              <text class="required">
                *
              </text>
              <text class="form-label">
                打印机Key
              </text>
            </view>
            <input
              v-model="feiyeForm.key"
              class="form-input"
              placeholder="请输入打印机Key"
            >
          </view>
          <view class="form-item">
            <view class="label-box">
              <text class="form-label">
                备注
              </text>
            </view>
            <input
              v-model="feiyeForm.note"
              class="form-input"
              placeholder="请输入备注信息"
            >
          </view>
        </view>
        <view class="feiye-footer">
          <button class="btn-cancel" @click="showFeiyeDialog = false">
            取消
          </button>
          <button class="btn-confirm" @click="saveFeiyePrinter">
            确定
          </button>
        </view>
      </view>
    </view>

    <custom-tabbar @navigate="handleNavigate"/>
  </view>
</template>

<script setup lang="ts">
import type {PayData, UserInfo, UserInfoData} from '@/api/user/types';
import {computed, onMounted, ref} from 'vue';
import {UserApi} from '@/api';
import customTabbar from '@/components/custom-tabbar/custom-tabbar.vue';
import usePermission from '@/hooks/use-permission';
import {useUserStore} from '@/store';
import AccountCacheManager from '@/utils/accountCache';
import {clearToken, getToken} from '@/utils/auth';
import {post} from '@/utils/request';

// 声明 Android 桥接类型
declare global {
  interface Window {
    Android?: {
      dDisconnectDevice: (id: string) => void;
      dConnectUsbDevices: (id: string) => void;
      dConnectBlueToothDevice: (address: string) => void;
      dIsDeviceConnected: () => boolean;
      dConnectedDeviceName: () => string;
      dConnectedDeviceId: () => string;
      dGetPairedBluetoothDeviceList: () => string;
      dGetUsbDeviceList: () => string;
      dStartBluetoothScan: (duration: number) => void;
      dGetScanResult: () => string;
      dPrintHtml: (html: string) => void;
    };
  }
}

// 页面数据
const loading = ref(false);
const userInfo = ref<UserInfoData>({} as UserInfoData);
const payData = ref<PayData>({} as PayData);
const cashierUserInfo = ref<UserInfo | null>(null);

// 用户store
const userStore = useUserStore();

// 打印机相关状态
const selectPrinterShow = ref(false);
const searchLoading = ref(false);
const elementLoadingText = ref('');
const blueDevice = ref<any[]>([]);
const usbDevice = ref<any[]>([]);
const printerList = ref<any[]>([]);
const connectDeviceId = ref('');
const disconnect = ref(false);
const currentPrinterName = ref('');

// 飞蛾打印机表单
const showFeiyeDialog = ref(false);
const feiyeForm = ref({
  id: null as number | null,
  name: '',
  num: '',
  key: '',
  note: '',
});

// 菜单数据
const menus = ref([
  {
    id: 1,
    icon: 'https://ceshiweb.picaime.com/static/images/user/menu1.png',
    name: '人员管理',
    route: '/pages/personnel/index',
  },
  {
    id: 2,
    icon: 'https://ceshiweb.picaime.com/static/images/user/menu1.png',
    name: '耗材商城',
    type: 'miniProgram',
    appId: 'wx1234567890abcdef', // 替换为实际的小程序 appId
    path: 'pages/index/index', // 替换为实际的小程序路径
  },
  {
    id: 3,
    icon: 'https://ceshiweb.picaime.com/static/images/user/menu3.png',
    name: '功能反馈',
    route: '/pages/feedback',
  },
  {
    id: 4,
    icon: 'https://ceshiweb.picaime.com/static/images/user/menu4.png',
    name: '经营文案',
    route: '/pages/copywriting',
  },
]);

// 设置菜单 - 使用computed动态生成
const settingsList = computed(() => [
  {
    id: 1,
    name: '选择打印机',
    description: currentPrinterName.value || '未连接',
    action: 'selectPrinter',
  },
  {id: 2, name: '打印配置', description: '', route: '/pages/common/defaultConfig/index'},
  {id: 3, name: '功能配置', description: '', route: '/pages/common/functionConfig/index'},
  {id: 4, name: '商户认证', description: '', route: '/pages/merchantAuth'},
  {id: 5, name: '关于我们', description: '', route: '/pages/common/aboutUs/index'},
  {
    id: 6,
    name: '当前版本',
    description: '1.2.1',
    action: 'checkVersion',
  },
]);

// 获取用户信息通过token
const fetchUserInfoByToken = async () => {
  try {
    const token = getToken();
    if (!token) {
      console.warn('未找到token');
      return;
    }

    const res = await UserApi.getUserInfoByToken({token});

    if (res.code === 200 && res.data) {
      cashierUserInfo.value = res.data;
      console.log('获取用户信息成功:', res.data);
    } else {
      console.error('获取用户信息失败:', res.msg);
    }
  } catch (error) {
    console.error('获取用户信息异常:', error);
  }
};

// 获取用户中心数据
const fetchUserCenterData = async () => {
  try {
    loading.value = true;

    // 使用uni原生loading提示
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });

    // 同时获取两个接口的数据
    await Promise.all([
      UserApi.getUserCenter().then((res) => {
        if (res.code === 200 && res.data) {
          userInfo.value = res.data.userinfo || {};
          payData.value = res.data.pay || {};
        }
      }),
      fetchUserInfoByToken(),
    ]);
  } catch (error) {
    console.error('获取用户中心数据失败:', error);
    uni.showToast({
      title: '获取用户数据失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
    uni.hideLoading();
  }
};

// 格式化到期时间
const formatExpireTime = (timestamp?: number) => {
  if (!timestamp) {
    return '';
  }
  const date = new Date(timestamp * 1000);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}年${month}月${day}日`;
};

// 续费功能
const renew = () => {
  uni.showToast({
    title: '续费功能开发中',
    icon: 'none',
  });
};

// 退出登录功能
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({
          title: '退出中...',
          mask: true,
        });

        // 清空用户信息
        userStore.resetInfo();
        // 清空token
        clearToken();
        // 清除多账户缓存
        AccountCacheManager.clearCache();

        uni.hideLoading();
        uni.showToast({
          title: '退出成功',
          icon: 'success',
        });

        // 延迟跳转到登录页面
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/common/login/index',
          });
        }, 800);
      }
    },
  });
};

// 页面跳转
const navigate = (item: any) => {
  // 如果是跳转小程序
  if (item.type === 'miniProgram') {
    wx.navigateToMiniProgram({
      shortLink: '#小程序://云友专业农副产品批发丨黄陂店/RulSvZNQ5aEuhYD',
      envVersion: 'trial',
      success(res) {
        console.log(res)
      },
    });
  }
  // 如果是打印机选择
  if (item.action === 'selectPrinter') {
    selectPrinter();
    return;
  }
  // 如果是版本检查
  if (item.action === 'checkVersion') {
    checkVersion();
    return;
  } else if (item.route) {
    // 普通页面跳转
    uni.navigateTo({
      url: item.route,
    });
  }
};

// 检查版本更新
const checkVersion = () => {
  uni.showLoading({
    title: '检查中...',
    mask: true,
  });

  // 模拟检查版本，延迟1秒显示结果
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '已是最新版本',
      icon: 'success',
      duration: 2000,
    });
  }, 1000);
};

// 检测是否为 Android 环境
const isAndroidEnv = () => {
  try {
    const nav = typeof navigator !== 'undefined' ? navigator : undefined;
    const w = typeof window !== 'undefined' ? window : undefined;
    const uaIsAndroid = !!(nav && /Android/i.test(nav.userAgent));
    const hasBridge = !!(w && w.Android);
    return uaIsAndroid || hasBridge;
  } catch (e) {
    return false;
  }
};

// 选择打印机
const selectPrinter = async () => {
  selectPrinterShow.value = true;

  // 获取飞蛾打印机列表
  try {
    const res: any = await post('/syapi/dayin/get_print_list', {data: {}});
    if (res.code === 200) {
      printerList.value = res.data || [];
    }
  } catch (e) {
    console.error('获取飞蛾打印机列表失败:', e);
  }

  // Android 环境获取蓝牙和 USB 打印机
  if (isAndroidEnv() && window.Android) {
    try {
      const blueRes = window.Android.dGetPairedBluetoothDeviceList();
      const usbRes = window.Android.dGetUsbDeviceList();

      if (blueRes && blueRes !== 'undefied') {
        const devices = JSON.parse(blueRes);
        // 显示所有蓝牙设备
        blueDevice.value = devices.filter((it: any) => it && it.name);
      }

      if (usbRes) {
        usbDevice.value = JSON.parse(usbRes);
      }

      // 获取当前连接状态
      disconnect.value = window.Android.dIsDeviceConnected();
      if (disconnect.value) {
        currentPrinterName.value = window.Android.dConnectedDeviceName();
        connectDeviceId.value = window.Android.dConnectedDeviceId();
      }
    } catch (e) {
      console.error('获取 Android 打印机失败:', e);
    }
  }
};

// 断开打印机连接
const disconnectPrint = () => {
  if (isAndroidEnv() && window.Android) {
    window.Android.dDisconnectDevice('123');
  }
  disconnect.value = false;
  connectDeviceId.value = '';
  currentPrinterName.value = '';
};

// 连接斯普瑞特蓝牙/USB打印机
const selectlyPrint = (item: any, type: number) => {
  if (!isAndroidEnv() || !window.Android) {
    uni.showToast({title: '当前环境不支持', icon: 'none'});
    return;
  }

  // 先断开已有连接
  window.Android.dDisconnectDevice('123');

  // 根据类型连接: 1=USB, 2=蓝牙
  if (type === 1) {
    window.Android.dConnectUsbDevices(item.id);
  } else {
    window.Android.dConnectBlueToothDevice(item.address);
  }

  searchLoading.value = true;
  elementLoadingText.value = '打印机连接中.........';

  setTimeout(() => {
    searchLoading.value = false;
    const connectResult = window.Android!.dIsDeviceConnected();

    if (!connectResult) {
      uni.showToast({title: '打印机未连接成功', icon: 'error'});
      disconnect.value = false;
      currentPrinterName.value = '';
    } else {
      uni.showToast({title: '打印机连接成功', icon: 'success'});
      currentPrinterName.value = type === 1 ? item.deviceName : item.name;
      connectDeviceId.value = type === 1 ? item.id : item.address;
      disconnect.value = true;
      selectPrinterShow.value = false;
    }
  }, 2000);
};

// 选择飞蛾打印机
const selectFeiyePrint = async (item: any) => {
  console.log('选择飞蛾打印机:', item);

  // 如果之前连接了本地打印机，断开
  if (disconnect.value) {
    disconnectPrint();
  }

  // 更新当前打印机名称
  currentPrinterName.value = item.name;

  // 关闭弹窗
  selectPrinterShow.value = false;

  // 调用接口保存打印机配置
  try {
    uni.showLoading({title: '保存中...', mask: true});

    const res: any = await post('/syapi/config/receiptsave', {
      data: {
        printer_name: item.name,
        printer_type: 1, // 飞蛾打印机
        fei_id: item.id,
      },
    });

    uni.hideLoading();

    if (res.code === 200) {
      uni.showToast({title: `已选择：${item.name}`, icon: 'success'});
    } else {
      uni.showToast({title: res.msg || '保存失败', icon: 'none'});
    }
  } catch (e) {
    uni.hideLoading();
    console.error('保存打印机配置失败:', e);
    uni.showToast({title: '保存失败，请重试', icon: 'none'});
  }
};

// 搜索蓝牙打印机
const searchPrint = () => {
  if (!isAndroidEnv() || !window.Android) {
    uni.showToast({title: '当前环境不支持', icon: 'none'});
    return;
  }

  window.Android.dStartBluetoothScan(3);
  searchLoading.value = true;
  elementLoadingText.value = '打印机搜索中.........';

  setTimeout(() => {
    searchLoading.value = false;
    const res = window.Android!.dGetScanResult();
    const devices = JSON.parse(res || '[]');

    // 显示所有搜索到的蓝牙设备
    blueDevice.value = devices.filter((it: any) => it && it.name);
  }, 4000);
};

// 处理导航事件
const handleNavigate = ({ type, url }: { type: string; url: string }): void => {
  if (type === 'navigateTo') {
    uni.navigateTo({ url });
  }
  else if (type === 'switchTab') {
    uni.switchTab({ url });
  }
};

// 添加飞蛾打印机
const addFeiyePrinter = () => {
  feiyeForm.value = {
    id: null,
    name: '',
    num: '',
    key: '',
    note: '',
  };
  showFeiyeDialog.value = true;
};

// 编辑飞蛾打印机
const editFeiyePrinter = (item: any) => {
  feiyeForm.value = {
    id: item.id,
    name: item.name,
    num: item.num,
    key: item.key,
    note: item.note || '',
  };
  showFeiyeDialog.value = true;
};

// 保存飞蛾打印机
const saveFeiyePrinter = async () => {
  // 表单验证
  if (!feiyeForm.value.name) {
    uni.showToast({title: '请输入打印机名称', icon: 'none'});
    return;
  }
  if (!feiyeForm.value.num) {
    uni.showToast({title: '请输入打印机编号', icon: 'none'});
    return;
  }
  if (!feiyeForm.value.key) {
    uni.showToast({title: '请输入打印机Key', icon: 'none'});
    return;
  }

  try {
    const result: any = await post('/syapi/dayin/addfeie', {data: feiyeForm.value});
    if (result.code === 200) {
      uni.showToast({title: '保存成功', icon: 'success'});
      printerList.value = result.data || [];
      showFeiyeDialog.value = false;
    } else {
      uni.showToast({title: result.msg || '保存失败', icon: 'error'});
    }
  } catch (e) {
    console.error('保存飞蛾打印机失败:', e);
    uni.showToast({title: '保存失败', icon: 'error'});
  }
};

// 删除飞蛾打印机
const deleteFeiyePrinter = async (id: number) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该打印机吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result: any = await post('/syapi/dayin/del_print', {data: {id}});
          if (result.code === 200) {
            uni.showToast({title: '删除成功', icon: 'success'});
            printerList.value = result.data || [];
          } else {
            uni.showToast({title: result.msg || '删除失败', icon: 'error'});
          }
        } catch (e) {
          console.error('删除飞蛾打印机失败:', e);
          uni.showToast({title: '删除失败', icon: 'error'});
        }
      }
    },
  });
};

// 用户页面首次加载时检查登录权限
onLoad(() => {
  usePermission();
});

// 每次显示页面时检查登录权限并刷新数据
onShow(() => {
  usePermission();
  fetchUserCenterData();
  initPrinterStatus();
});

// 初始化打印机状态
const initPrinterStatus = async () => {
  // 从接口获取打印机信息
  try {
    const res: any = await post('/syapi/config/receiptField', {data: {}});
    if (res.code === 200 && res.data?.use_printer_name) {
      currentPrinterName.value = res.data.use_printer_name;
    }
  } catch (e) {
    console.error('获取打印机配置失败:', e);
  }

  // Android 环境检查连接状态
  if (isAndroidEnv() && window.Android) {
    try {
      disconnect.value = window.Android.dIsDeviceConnected();
      if (disconnect.value) {
        const deviceName = window.Android.dConnectedDeviceName();
        const deviceId = window.Android.dConnectedDeviceId();
        if (deviceName) {
          currentPrinterName.value = deviceName;
          connectDeviceId.value = deviceId;
        }
      }
    } catch (e) {
      console.error('初始化打印机状态失败:', e);
    }
  }
};

// 初始化页面数据
onMounted(() => {
  fetchUserCenterData();
  initPrinterStatus();
});
</script>

<style scoped>
.page-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.top-section {
  position: relative;
  width: 100%;
  background-color: #fff;
}

.top-profile {
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  margin-bottom: 25rpx;
}

.profile-pic {
  width: 110rpx;
  height: 110rpx;
  background-color: #f5f5f5;
  border-radius: 50%;
}

.user-info {
  display: flex;
  flex: 1;
  flex-direction: column;
  margin-left: 20rpx;
}

.user-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.user-subtitle {
  margin-top: 8rpx;
  font-size: 28rpx;
  color: #666;
}

.right-icon {
  width: 36rpx;
  height: 36rpx;
}

.info-card {
  position: relative;
  display: flex;
  align-items: center;
  width: 92%;
  height: 160rpx;
  margin: 30rpx auto 0;
  background-color: #4f6752;
  background-image: none;
  border-radius: 12rpx;
}

.info-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 30rpx;
}

.left-section {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.diamond-tag {
  display: flex;
  align-items: center;
}

.diamond-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.tag-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #f2a922;
}

.expiry-text {
  margin-top: 14rpx;
  font-size: 24rpx;
  color: rgb(255 255 255 / 90%);
}

.renew-button {
  position: absolute;
  top: 50rpx;
  right: 30rpx;
  min-width: 160rpx;
  height: 60rpx;
  padding: 0 25rpx;
  font-size: 26rpx;
  line-height: 60rpx;
  color: #705336;
  background: linear-gradient(160deg, #efcc98 0%, #deae68 100%);
  border: none;
  border-radius: 30rpx;
  box-shadow: 0 2rpx 4rpx rgb(0 0 0 / 20%);
}

/* 数据卡片样式 */
.data-card {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 30rpx 20rpx;
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgb(0 0 0 / 5%);
}

.data-item {
  position: relative;
  display: flex;
  flex: 1;
  flex-direction: column;
  align-items: center;
}

.data-item:not(:last-child)::after {
  position: absolute;
  top: 10rpx;
  right: 0;
  width: 1rpx;
  height: 80%;
  content: '';
  background-color: #f0f0f0;
}

.data-value {
  margin-bottom: 8rpx;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.data-label {
  font-size: 24rpx;
  color: #999;
}

.menu-card {
  padding: 0;
  margin: 20rpx;
  overflow: hidden;
  background-color: #fff;
  border-radius: 12rpx;
}

.menu-items {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  padding: 30rpx 10rpx;
  background-color: #fff;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.menu-icon {
  width: 72rpx;
  height: 72rpx;
  padding: 16rpx;
  margin-bottom: 12rpx;
  background-color: #e6ebe7;
  border-radius: 10rpx;
}

.menu-text {
  font-size: 26rpx;
  color: #333;
}

.settings-list {
  margin: 20rpx;
  overflow: hidden;
  background-color: #fff;
  border-radius: 12rpx;
}

.settings-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.settings-item:last-child {
  border-bottom: none;
}

.settings-text {
  flex: 1;
}

.settings-name {
  font-size: 30rpx;
  color: #333;
}

.settings-right {
  display: flex;
  align-items: center;
}

.settings-description {
  margin-right: 10rpx;
  font-size: 26rpx;
  color: #999;
}

.settings-right-icon {
  width: 30rpx;
  height: 30rpx;
}

/* 头像样式 */
.avatar-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  background: #959596;
  border-radius: 12px;
}

.avatar-text {
  font-size: 24px;
  font-weight: bold;
  color: #fff;
}

/* 打印机选择对话框样式 */
.printer-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.printer-modal-content {
  width: 90%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.printer-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #fff;
}

.header-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.add-feie-btn {
  background-color: #4ca75b;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.close-icon {
  font-size: 40rpx;
  color: #d81e06;
  cursor: pointer;
  font-weight: bold;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
  font-size: 28rpx;
}

.loading-icon {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #fff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.printer-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  min-height: 400rpx;
  max-height: 60vh;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  color: #999;
  font-size: 28rpx;
  text-align: center;
}

.sub-tip {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #ccc;
}

.printer-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  border: 1rpx solid #dcdfe6;
  transition: all 0.3s;
}

.printer-item:active {
  background-color: #f0f0f0;
}

.feiye-item {
  border: 1rpx solid #e0e0e0;
  background: linear-gradient(135deg, #ffffff 0%, #f9f9f9 100%);
}

.printer-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  cursor: pointer;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.info-col {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.note-row {
  border-top: 1rpx dashed #e5e5e5;
  padding-top: 12rpx;
  margin-top: 8rpx;
}

.label {
  font-size: 26rpx;
  color: #909399;
  flex-shrink: 0;
}

.value {
  font-size: 28rpx;
  color: #303133;
  margin-left: 12rpx;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.value.bold {
  font-weight: 600;
  border: none;
  background: none;
  padding: 0;
  font-size: 30rpx;
  color: #1a1a1a;
  margin-left: 0;
}

.printer-note {
  font-size: 24rpx;
  color: #606266;
  font-weight: 500;
}

.note-text {
  color: #aac7ef;
  font-weight: normal;
}

.printer-actions {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  margin-left: 20rpx;
  flex-shrink: 0;
}

.action-btn {
  width: 68rpx;
  height: 68rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  cursor: pointer;
}

.edit-btn {
  background-color: #ecf5ff;
}

.delete-btn {
  background-color: #fef0f0;
}

.action-btn:active {
  transform: scale(0.92);
  opacity: 0.7;
}

.action-text {
  font-size: 36rpx;
}

.printer-footer {
  padding: 24rpx 30rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
}

.search-btn {
  width: 100%;
  height: 80rpx;
  background-color: #4ca75b;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(76, 167, 91, 0.2);
}

/* 飞蛾打印机对话框样式 */
.feiye-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1002;
  display: flex;
  align-items: center;
  justify-content: center;
}

.feiye-modal-content {
  width: 85%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.feiye-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.feiye-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.feiye-close {
  font-size: 40rpx;
  color: #999;
}

.feiye-body {
  max-height: 60vh;
  overflow-y: auto;
}

.feiye-body .form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 87%;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
}

.label-box {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
}

.required {
  color: #ff4d4f;
  margin-right: 5rpx;
  font-size: 28rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
}

.form-input {
  width: 100%;
  height: 70rpx;
  background-color: #f5f5f5;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.feiye-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 30rpx;
  border: none;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #666;
}

.btn-confirm {
  background-color: #4ca75b;
  color: #fff;
}
</style>
